﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using System.IO;
namespace WpfApplicationExperimental
{
    /// <summary>
    /// Interaction logic for FileIconControl.xaml
    /// </summary>
    public partial class FileIconControl : UserControl
    {
        public FileIconControl()
        {
            InitializeComponent();
        }
        
        //public System.Diagnostics.Process Procces;
       // public static event EventHandler<AttachmentEventArgs> OnExit;


        public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
        {
            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(source.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
        }

        public DataAccesLayer.Attachment Attachment
        {
            get { return (DataAccesLayer.Attachment)GetValue(AttachmentProperty); }
            set { SetValue(AttachmentProperty, value);}
            
        }

        public static readonly DependencyProperty AttachmentProperty =
        DependencyProperty.Register(
        "Attachment",
        typeof(DataAccesLayer.Attachment),
        typeof(FileIconControl),
        new FrameworkPropertyMetadata(
            new DataAccesLayer.Attachment(),
            FrameworkPropertyMetadataOptions.None,
            new PropertyChangedCallback(AttachmentChangedCallback),
           new CoerceValueCallback(CoerceAttachmentReading)));

        public event RoutedEventHandler OnAttachmentChanged;
        public event RoutedEventHandler OnAttachmentSaved;
        public event RoutedEventHandler OnAttachmentInserted;
        public event RoutedEventHandler OnExitingDocument;


       public static void AttachmentChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
       {
           //how to get an instance of the object that is the fucking stupid solution 1 hour for this
           DataAccesLayer.Attachment value = e.NewValue as DataAccesLayer.Attachment;

           FileIconControl imageControl = d as FileIconControl;
           if (value == null)
           {
              
               imageControl.image1.Source =null;  
               return;
           }
           System.Drawing.Bitmap image = IconReader.GetFileIcon(value.Name, IconReader.IconSize.Small, false).ToBitmap();
           imageControl.image1.Source  = loadBitmap(image);
       }


        public static object CoerceAttachmentReading (DependencyObject d, object value)
       {

            return value ;
       }
        /// <summary>
        /// SelectedDateProperty property changed handler.
        /// </summary>
        /// <param name="d">DatePicker that changed its SelectedDate.</param>
        /// <param name="e">DependencyPropertyChangedEventArgs.</param>
        private static void OnSelectedDateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

        }

        private void UserControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (Attachment == null)
                UploadImage();
            else
                OpenAttachment();
        }

        System.Diagnostics.Process Procces;

        private void OpenAttachment()
        {
            String PersonalFolder =Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
            string TempPath = SaveAttachment(PersonalFolder);
            Procces = System.Diagnostics.Process.Start(TempPath);
            Procces.WaitForExit();

            Stream  newFile = new FileStream(TempPath , FileMode.Open);
            
            byte[] MyData = Attachment.Data.ToArray();
            Stream oldFile = new MemoryStream(MyData, 0, System.Convert.ToInt32(MyData.Count()));
  
            if (AreStreamsSame(newFile, oldFile) != true)
            {
                Procces_Exited(this, new EventArgs());
                modifidedFile = newFile;
            }
 
        }

        public  Stream modifidedFile;

        void Procces_Exited(object sender, EventArgs e)
        {
            if (this.OnExitingDocument != null)
                OnExitingDocument(this, new RoutedEventArgs());
        }

        private void UploadImage()
        {
            System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filepa = dlg.FileName;

                FileStream fs = new FileStream(filepa, FileMode.OpenOrCreate, FileAccess.Read);

                byte[] MyData = new byte[fs.Length];
                fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));

                char MyChar = '\\';
                string[] hg = filepa.Split(MyChar);
                string h = hg[hg.Length - 1];

                Attachment.Name = h;
                Attachment.Data = new System.Data.Linq.Binary(MyData);

                //  System.Drawing.Icon icon  =  IconReader.GetFileIcon(filepa, IconReader.IconSize.Small, false);
                if (OnAttachmentChanged != null)
                    OnAttachmentChanged(Attachment, new RoutedEventArgs());

                new DataAccesLayer.EQualDataLayerFactory().UpdateDataBase();
            }
        }

        private string  SaveAttachment(string  path )
        {

            string filepa = path +"/"+ Attachment.Name;

            FileStream fs = new FileStream(filepa, FileMode.Create, FileAccess.Write);

            byte[] MyData = Attachment.Data.ToArray();

            fs.Write(MyData, 0, System.Convert.ToInt32(MyData.Count()));

            fs.Close();
 
            return filepa;
        }

        private bool AreStreamsSame(Stream fs1, Stream fs2)
        {
            int file1byte;
            int file2byte;

            // Check the file sizes. If they are not the same, the files 
            // are not the same.
            if (fs1.Length != fs2.Length)
            {
                // Close the file
                fs1.Close();
                fs2.Close();

                // Return false to indicate files are different
                return false;
            }

            // Read and compare a byte from each file until either a
            // non-matching set of bytes is found or until the end of
            // file1 is reached.
            do
            {
                // Read one byte from each file.
                file1byte = fs1.ReadByte();
                file2byte = fs2.ReadByte();
            
            }
            while ((file1byte == file2byte) && (file1byte != -1));

            // Close the files.
            fs1.Close();
            fs2.Close();

            // Return the success of the comparison. "file1byte" is 
            // equal to "file2byte" at this point only if the files are 
            // the same.
            return ((file1byte - file2byte) == 0);
        }
    }
}
